const db = require('../config/db');
const geoip = require('geoip-lite'); // 用于IP地理位置解析
const useragent = require('useragent'); // 用于解析UA信息
const DEFAULT_COVER_IMAGE = 'default_cover.jpg';

// 工具函数
function formatPublishTime() {
    const now = new Date();
    return now.toISOString().slice(0, 19).replace('T', ' ');
}

function parseUserAgent(ua) {
    const agent = useragent.parse(ua);
    return {
        browser: agent.toAgent(),
        os: agent.os.toString(),
        device: agent.device.toString(),
        isMobile: agent.device.isMobile
    };
};
function normalizeTags(input) {
    // 已经是数组直接返回
    console.log(Array.isArray(input),'input is array?')
    if (Array.isArray(input)){
        return input.join(',')
    }else{
        return input;
    }
}

/**
 * 文章添加接口逻辑
 */
exports.addArticle = (req, res) => {
    try {
        // 获取请求体数据
        let { title, content, cover_image, category, summary, deleted = 0, tags } = req.body;

        // 参数验证
        if (!title || !content || !category || !summary || !tags) {
            throw new Error('标题、内容、摘要、分类和标签是必填项');
        }

        // 默认封面图片
        cover_image = cover_image || DEFAULT_COVER_IMAGE;

        // 格式化时间
        const publish_time = formatPublishTime();

        // 格式化 tags
        tags = normalizeTags(tags);
        // 执行 SQL 语句
        const sql = 'INSERT INTO article (title, content, cover_image, category, deleted, publish_time, summary, tags, view_count) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 0)';
        const values = [title, content, cover_image, category, deleted, publish_time, summary, tags];

        db.query(sql, values, (err, result) => {
            if (err) {
                console.error('数据库错误:', err.message);
                return res.status(500).send({
                    code: 1, msg: '服务器错误', data: {
                        error: err.message
                    },
                    error: err.message
                });
            }
            res.status(200).send({
                code: 0,
                msg: '文章添加成功',
                data: { article_id: result.insertId }
            });
        });
    } catch (error) {
        console.error('参数验证错误:', error.message);
        res.status(400).send({ code: 1, msg: error.message });
    }
};

/** 
 * 文章查询接口逻辑
 */
exports.listArticle = (req, res) => {
    // 获取请求体数据
    let { category, page = 1, size = 10 } = req.query;
    page = (page - 1) * size;

    // 动态生成查询条件
    let pageSql, countSql, queryParams;

    if (category && category !== 'all') {
        pageSql = `SELECT * FROM article WHERE deleted=0 AND category=? ORDER BY publish_time DESC LIMIT ?,?`;
        countSql = `SELECT COUNT(*) AS count FROM article WHERE deleted=0 AND category=?`;
        queryParams = [category, Number(page), Number(size)];
    } else {
        pageSql = `SELECT * FROM article WHERE deleted=0 ORDER BY publish_time DESC LIMIT ?,?`;
        countSql = `SELECT COUNT(*) AS count FROM article WHERE deleted=0`;
        queryParams = [Number(page), Number(size)];
    }

    // 执行查询文章列表的 SQL 语句
    db.query(pageSql, queryParams, (err, resPage) => {
        if (err) return res.send({ code: 1, msg: err.message });

        // 执行查询文章总数的 SQL 语句
        const countQueryParams = category && category !== 'all' ? [category] : [];
        db.query(countSql, countQueryParams, (err, result) => {
            if (err) return res.send({ code: 1, msg: err.message });

            res.send({
                code: 0,
                msg: '文章查询成功',
                data: {
                    list: resPage,
                    total: result[0].count,
                }
            });
        });
    });
};

/**
 * 文章修改接口逻辑
 */
exports.updateArticle = (req, res) => {
    // 获取请求参数
    let { id, title, content, cover_image, category, summary, deleted = 0, tags } = req.body;
    // ⭐ 优先标准化标签格式
    console.log(tags,'-----');
    if (tags !== undefined) {
        tags = normalizeTags(tags);
    }
    // tags = tags.split(',')
    console.log(tags,'+++++');
    // 参数验证
    if (!id || isNaN(Number(id))) {
        return res.status(400).send({ code: 1, msg: '无效的ID' });
    }

    // 检查是否有提供更新字段 (注意空数组[]也视为有效更新)
    const hasUpdates = title || content || cover_image || category || summary ||
        tags !== undefined || deleted !== undefined;
    if (!hasUpdates) {
        return res.status(400).send({ code: 1, msg: '未提供修改内容' });
    }

    // 初始化 SQL 语句和参数数组
    let sql = `UPDATE article SET `;
    const updates = [];
    const values = [];

    // 动态构建 SQL 语句
    if (title) {
        updates.push('title=?');
        values.push(title);
    }
    if (content) {
        updates.push('content=?');
        values.push(content);
    }
    if (cover_image !== undefined) {
        updates.push('cover_image=?');
        // 使用空字符串表示清空封面图
        values.push(cover_image === '' ? '' : (cover_image || DEFAULT_COVER_IMAGE));
    }
    if (category) {
        updates.push('category=?');
        values.push(category);
    }
    if (summary) {
        updates.push('summary=?');
        values.push(summary);
    }
    if (tags !== undefined) {
        updates.push('tags=?');
        // tags 已经标准化为数组格式
        // values.push(JSON.stringify(tags));
         values.push(tags)
    }
    if (deleted !== undefined) {
        updates.push('deleted=?');
        values.push(deleted);
    }

    // 追加更新时间
    updates.push('update_time=NOW()');

    // 拼接 SQL 语句
    sql += updates.join(', ') + ' WHERE id=?';
    values.push(Number(id));

    // 执行 SQL 查询
    db.query(sql, values, (err, result) => {
        if (err) {
            console.error('数据库错误:', err);
            return res.status(500).send({ code: 1, msg: '服务器错误', error: err.message });
        }
        if (result.affectedRows !== 1) {
            return res.status(404).send({ code: 1, msg: '文章未找到或未修改' });
        }
        res.status(200).send({
            code: 0,
            msg: '修改成功',
            data: { id }
        });
    });
};

/**
 * 文章删除接口逻辑
 */
exports.deleteArticle = (req, res) => {
    // 获取请求参数（从query获取）
    const { id } = req.query;

    // 参数验证
    if (!id || isNaN(Number(id))) {
        return res.status(400).send({ code: 1, msg: '无效的ID' });
    }

    // 执行sql语句
    const sql = `UPDATE article SET deleted=1 WHERE id = ? AND deleted = 0`;
    db.query(sql, [Number(id)], (err, result) => {
        if (err) {
            console.error(err);
            return res.status(500).send({ code: 1, msg: '服务器错误' });
        }
        if (result.affectedRows !== 1) {
            return res.status(404).send({ code: 1, msg: '删除失败，找不到对应的文章或文章已删除' });
        }
        res.send({
            code: 0,
            msg: '删除成功'
        });
    });
};

/**
 * 根据文章ID获取文章详情接口逻辑
 */
exports.getArticleDetail = (req, res) => {
    try {
        // 从请求参数获取文章ID
        const { id } = req.query;

        // 参数验证
        if (!id || isNaN(Number(id))) {
            return res.status(400).send({ code: 1, msg: '无效的文章ID' });
        }

        // 构建SQL查询语句
        const sql = `
                SELECT 
                    id, 
                    title, 
                    content, 
                    cover_image, 
                    category, 
                    DATE_FORMAT(publish_time, '%Y-%m-%d %H:%i:%s') AS publish_time, 
                    summary, 
                    tags
                FROM article 
                WHERE id = ? AND deleted = 0
            `;

        // 执行查询
        db.query(sql, [Number(id)], (err, results) => {
            if (err) {
                console.error('数据库查询错误:', err);
                return res.status(500).send({ code: 1, msg: '服务器错误', error: err.message });
            }

            // 检查文章是否存在
            if (results.length === 0) {
                return res.status(404).send({ code: 1, msg: '文章不存在或已被删除' });
            }

            // 处理结果
            const article = results[0];

            // 将tags从JSON字符串解析为数组
            try {
                article.tags = JSON.parse(article.tags);
            } catch (e) {
                // 如果解析失败，保持原始值
                console.warn('标签解析失败:', e.message);
            }

            // 返回文章详情
            res.status(200).send({
                code: 0,
                msg: '获取文章详情成功',
                data: article
            });
        });
    } catch (error) {
        console.error('获取文章详情错误:', error.message);
        res.status(500).send({ code: 1, msg: '服务器内部错误' });
    }
};

/**
 * 文章统计接口逻辑
 */
exports.getArticleStatistics = (req, res) => {
    try {
        // 获取查询参数
        const {
            id,
            title,
            category,
            start_date,
            end_date,
            type = 'daily',
            metrics = ['pv', 'uv'],
            limit = 10,
            include_details = false
        } = req.query;

        // 构建基础查询条件
        let whereClause = 'WHERE deleted=0';
        const queryParams = [];

        if (id) {
            whereClause += ' AND a.id = ?';
            queryParams.push(id);
        }
        if (title) {
            whereClause += ' AND a.title LIKE ?';
            queryParams.push(`%${title}%`);
        }
        if (category) {
            whereClause += ' AND a.category = ?';
            queryParams.push(category);
        }
        if (start_date && end_date) {
            whereClause += ' AND v.visit_time BETWEEN ? AND ?';
            queryParams.push(start_date, end_date);
        }

        // 确定时间分组格式
        let dateFormat;
        switch (type) {
            case 'daily':
                dateFormat = '%Y-%m-%d';
                break;
            case 'weekly':
                dateFormat = '%Y-%u'; // 年-周数
                break;
            case 'monthly':
                dateFormat = '%Y-%m';
                break;
            case 'yearly':
                dateFormat = '%Y';
                break;
            default:
                dateFormat = '%Y-%m-%d';
        }

        // 构建统计SQL
        const statsSql = `
            SELECT 
                DATE_FORMAT(v.visit_time, ?) AS period,
                COUNT(v.id) AS pv,
                COUNT(DISTINCT v.ip_address) AS uv,
                a.title,
                a.category
            FROM article_visits v
            JOIN article a ON v.article_id = a.id
            ${whereClause}
            GROUP BY period, a.id
            ORDER BY pv DESC
            LIMIT ?
        `;
        queryParams.unshift(dateFormat, Number(limit));

        // 执行统计查询
        db.query(statsSql, queryParams, (err, statsResult) => {
            if (err) {
                console.error('统计查询错误:', err);
                return res.status(500).send({ code: 1, msg: '统计查询失败' });
            }

            // 如果需要详细数据
            let details = [];
            if (include_details && id) {
                const detailsSql = `
                    SELECT * FROM article_visits
                    WHERE article_id = ?
                    ORDER BY visit_time DESC
                    LIMIT 100
                `;
                db.query(detailsSql, [id], (err, detailsResult) => {
                    if (err) {
                        console.error('详细数据查询错误:', err);
                        // 即使详细数据失败也返回统计结果
                        return res.send({
                            code: 0,
                            msg: '统计成功（详细数据获取失败）',
                            data: { stats: statsResult }
                        });
                    }
                    details = detailsResult;
                    sendResponse(statsResult, details);
                });
            } else {
                sendResponse(statsResult, details);
            }
        });

        // 发送响应
        function sendResponse(stats, details) {
            res.send({
                code: 0,
                msg: '统计成功',
                data: {
                    stats,
                    details: include_details ? details : undefined
                }
            });
        }

    } catch (error) {
        console.error('统计处理错误:', error);
        res.status(500).send({ code: 1, msg: '统计处理失败' });
    }
};

/**
 * 记录文章访问接口逻辑
 */
exports.recordArticleVisit = (req, res) => {
    try {
        const { article_id, ip, ua } = req.body;

        // 解析地理位置
        const geo = geoip.lookup(ip);
        const location = geo ? `${geo.country}-${geo.region}-${geo.city}` : '未知地区';

        // 解析设备信息
        const deviceInfo = parseUserAgent(ua);

        // 记录访问日志
        const visitSql = `
            INSERT INTO article_visits 
            (article_id, ip_address, user_agent, location, device_type, browser, os)
            VALUES (?, ?, ?, ?, ?, ?, ?)
        `;
        const visitValues = [
            article_id,
            ip,
            ua,
            location,
            deviceInfo.isMobile ? 'Mobile' : 'Desktop',
            deviceInfo.browser,
            deviceInfo.os
        ];

        db.query(visitSql, visitValues, (err, result) => {
            if (err) {
                console.error('访问记录错误:', err);
                return res.status(500).send({ code: 1, msg: '访问记录失败' });
            }

            // 更新文章阅读量
            const updateSql = 'UPDATE article SET view_count = view_count + 1 WHERE id = ?';
            db.query(updateSql, [article_id], (err, updateResult) => {
                if (err) {
                    console.error('阅读量更新错误:', err);
                    // 即使阅读量更新失败也返回成功，因为访问已记录
                }

                res.status(201).send({
                    code: 0,
                    msg: '访问记录成功'
                });
            });
        });
    } catch (error) {
        console.error('访问记录处理错误:', error);
        res.status(500).send({ code: 1, msg: '访问记录处理失败' });
    }
};

/**
 * 增加文章阅读量接口逻辑
 */
exports.incrementArticleView = (req, res) => {
    try {
        const { id, increment = 1 } = req.body;

        // 参数验证
        if (!id || isNaN(Number(id))) {
            return res.status(400).send({ code: 1, msg: '无效的ID' });
        }

        // 更新阅读量
        const updateSql = 'UPDATE article SET view_count = view_count + ? WHERE id = ?';
        db.query(updateSql, [Number(increment), Number(id)], (err, result) => {
            if (err) {
                console.error('阅读量更新错误:', err);
                return res.status(500).send({ code: 1, msg: '阅读量更新失败' });
            }

            if (result.affectedRows !== 1) {
                return res.status(404).send({ code: 1, msg: '文章未找到' });
            }

            res.send({
                code: 0,
                msg: '阅读量更新成功'
            });
        });
    } catch (error) {
        console.error('阅读量更新处理错误:', error);
        res.status(500).send({ code: 1, msg: '阅读量更新处理失败' });
    }
};